<template>
  <div style="padding: 0 15px;" v-loading="loading">
    <el-collapse-transition>
      <div v-show='listWrap'>
        <el-form :inline="true" :model="search" class="search" @keyup.enter.native="reList" style="height:auto;">
          <el-form-item>
            <el-input v-model="search.modelTitleKeyword" placeholder="搜索模版名称" clearable prefix-icon="el-icon-search"
              @clear="reList" style="width:150px;padding-left:5px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="reList()" title='点击搜索'>搜索</el-button>
            <el-button plain color="#6e6ef1" size="small" title='点击去新增模版' @click="handleEditOrAdd()">新建模板</el-button>
          </el-form-item>
        </el-form>
        <el-table  style="width: 100%;" :data="tableData" border align="center" highlight-current-row stripe table-layout='auto'>
          <el-table-column prop="model_title" label="评价模板标题"></el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#409EFF" inactive-color="#cccccc"  active-value='1' inactive-value='0' @change="changeSwitch($event, scope.row)" >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="insertTimeStr" label="创建日期"  width="180"  align="center"></el-table-column>
        <el-table-column  fixed="right" label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-link  type="primary" @click="handleCopy(scope.row)"  size="small" :title="'复制【'+scope.row.model_title +'】'">复制</el-link>
            <el-link  type="primary" @click="onView(scope.row.id)"  size="small" :title="'预览【'+scope.row.model_title +'】'">预览</el-link>
            <el-link  type="primary" @click="handleEditOrAdd(scope.row)"  size="small" :title="'编辑【'+scope.row.model_title +'】'">编辑</el-link>
            <el-popconfirm title="确定删除吗？"  @confirm="handleDel(scope.row)">
              <el-link type="danger"  slot="reference" size="small" :title="'删除【'+scope.row.model_title +'】'">删除</el-link>
            </el-popconfirm>
          </template>
        </el-table-column>
       </el-table>
        <!-- 分页 -->
        <el-pagination :currentPage=search.pageNo :page-size=search.pageSize :page-sizes="[10, 20,40, 50, 100]" :hide-on-single-page="allTotal==0"
          layout="total, sizes, prev, pager, next, jumper" :total="allTotal" @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-collapse-transition>
    <!-- :hide-on-single-page="allTotal<20" -->
    <!-- 复制模板 -->
    <el-dialog title="复制模版" :visible.sync="copyDialog" width="36%">
        <div class="formView">
          <el-form :model="copyForm" :rules="rules" ref="copyForm" >
              <el-form-item label="评价计划名称" prop="model_title" >
                  <el-input v-model="copyForm.model_title" maxlength="20" style='width: 360px;'></el-input>
              </el-form-item>
          </el-form>
        </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="copyDialog = false">取 消</el-button>
        <el-button type="primary"  @click="copySave">复制</el-button>
      </span>
    </el-dialog>
   <!-- 预览模板 -->
   <el-dialog title="预览模板" :visible.sync="dialogVisible" width="440px" height='774' id="viewWrap" custom-class="viewWrap" style="margin-top:-10vh;">
            <div id="completeDiv" ref="completeDiv" class='viewBG' >
              <iframe ref="myIframe" :src="completeTask"  width="100%" style="border:none; height: 100%;"></iframe>
            </div>
        </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'List',
  data () {
    return {
      // 模版列表
      tableData: [],
      loading: false,
      listWrap: true,
      // 总条数
      allTotal: 0,
      search: {
        'modelTitleKeyword': '',
        'status': '',
        'pageNo': 1,
        'pageSize': 10
      },
      date: [],
      nowView: '',
      org_name: '',
      image: '',
      sealShow: true,
       time: '',
      dialogInfoVisible: false, // 编辑模板窗口
      // 要复制的对象
      copyForm: {
        id: '',
        model_title: '',
        title: ''
      },
      rules: {
        model_title: [
            { required: true, message: '请输入模版名称', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
          ]
      },
      // 复制窗口
      copyDialog: false,
      flagTime: '',
      pickerOptions: {
          // 最长选择2个月
          onPick: ({maxDate, minDate}) => {
              this.flagTime= minDate.getTime()
              if (maxDate) {
                this.flagTime= ''
              }
            },
          disabledDate: (time) => {
              if (this.flagTime!== '') {
                const one = 30 * 24 * 3600 * 1000 * 2
                const minTime = this.flagTime- one
                const maxTime = this.flagTime+ one
                return time.getTime() < minTime || time.getTime() > maxTime
              }
            }
        },
        // 预览窗口
        dialogVisible: false,
        completeTask: ''
    }
  },
  mounted() {
      // this.restaurants = this.loadAll()
  },
  watch: {
  },
  created () {
    let _this = this
    this.detailData = []
    sessionStorage.removeItem('editTemplate')
    _this.list()
  },
  computed: {
  },
  methods: {
    // 预览
    onView(planId) {
      const _this=this
      this.dialogVisible = true
      _this.completeTask = window.location.origin+'/SmartEvaluatePages/mob/index.html#/view?org_id=' + sessionStorage.org_id + '&token='+sessionStorage.token + '&udid=' + sessionStorage.udid + '&mid=' + planId +'&t=' + new Date().getTime()
      this.$nextTick(() => {
        document.getElementById('completeDiv').innerHTML='<iframe ref="myIframe" src="'+_this.completeTask+'"  width="100%" style="border:none; height: 100%;"></iframe>'
      })
    },
    // 只能输入小数和整数35-42
    checkedNumber(value, obj) {
      value = value.replace(/[^\d|.]/g, '')
    },
    // 提问输入自动完成
    // querySearch(queryString, cb) {
    //     var restaurants = this.restaurants
    //     var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
    //     // 调用 callback 返回建议列表的数据
    //     cb(results)
    //   },
      // createFilter(queryString) {
      //   return (restaurant) => {
      //     return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      //   }
      // },
      // loadAll() {
      //   let allTemperatureArray = []
      //   let InitialNumber = 35
      //   for (let a = 350, b = 430; a < b; a++) {
      //     allTemperatureArray.push({ 'value': InitialNumber.toFixed(1), 'address': '℃' })
      //     InitialNumber += 0.1
      //   }
      //   return allTemperatureArray
      // },
      // handleSelect(item, i) {
      //   console.log(item)
      //   this.allTemperature[i] = item.value
      //   this.list()
      // },
    // test(value, i) {
     //   this.allTemperature[i || 1].value = 36
    //   this.$forceUpdate()
    // },
    // timeChange(e, b) {
    //   if (typeof e !== 'object') {
    //      this.data = [e, e]
    //   }
    //   this.search.pageNo=1
    //   this.list()
    // },
    // 本地数据生成班主任任课
    dealLocalData(okFun) {
      let mapRK = JSON.parse(sessionStorage.getItem('mapRK'))
      let mapBZR = JSON.parse(sessionStorage.getItem('mapBZR'))
      let allData = mapBZR.concat(mapRK)

      let allGClassId = []
      let gradeIndex = 0
      // 生成年级班级信息
      for (var i = allData.length - 1; i >= 0; i--) {
          var obj = allData[i]
          var gradeId = obj.grade_id
          // 年级信息
          let gradeObj = {
              grade_id: obj.grade_id,
              grade_name: obj.grade_name,
              grade_number: obj.grade_number,
              clasList: []
            }
          // 班级信息
          let classObj = {
                    clas_id: obj.clas_id,
                    clas_name: obj.clas_name
                  }

          let allClassId = []
          // let allClass = []
          if (!allGClassId.includes(obj.clas_id)) {
            allGClassId.push(obj.clas_id)
          }
          // 判断年级是否存在
          if (this.allClass[gradeId] === undefined) {
              this.allClass[gradeId] = gradeIndex
              gradeObj.clasList.push(classObj)
              allClassId.push(obj.clas_id)
              this.allGrade.push(gradeObj)
              gradeIndex += 1
          } else {
              // 查询该年级下是否已包含本班级
              let targetGrade = this.allGrade[this.allClass[gradeId]]
              let isHas = false
              for (var a = 0, b = targetGrade.clasList.length; a < b; a++) {
                 let objId = targetGrade.clasList[a].clas_id
                 if (objId === classObj.clas_id) {
                  isHas = true
                  break
                 }
              }
              if (!isHas) {
                // 判断班级是否重复
                allClassId.push(obj.clas_id)
                targetGrade.clasList.push(classObj)
              }
          }
      };
      // 生成班级年级关联
      this.allGrade.map(item => {
        let allClassId = []
        item.clasList.map(item => {
          allClassId.push(item.clas_id)
        })

        item.clasList.unshift({
          clas_id: allClassId.join('_'),
          clas_name: '全部班级'
        })

        this.allClass[item.grade_id] = item.clasList
      })

      this.allGrade.unshift({
          grade_id: 1000000,
          grade_number: 0,
          grade_name: '全部年级',
          clasList: [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
        })
        this.allClass[1000000] = [{
            clas_id: allGClassId.join('_'),
            clas_name: '全部班级'
          }]
      // 年级排序
      this.allGrade.sort(function(a, b) {
          if (a.grade_number < b.grade_number) {
              return -1
          }
          if (a.grade_number > b.grade_number) {
            return 1
          }
          return 0
      })

      // 设置默认值
      this.search.grade = 1000000
      this.getNowAllClass = this.allClass[1000000]
      this.search.search_class = this.allClass[1000000][0].clas_id

      console.log(this.allGrade)
      if (okFun) { okFun() }
    },
    // 获取模板列表
    async list () {
      this.loading = true
      const res = await this.$api.add.list.get(this.search)
      if (res.code === 200) {
        this.tableData = res.data.data
        this.tableData.map(item => { item.status=item.status.toString() })
        this.loading = false
        // 分页
        this.allTotal = res.data.total
      } else {
        this.loading = false
        this.$alert(res.message, '提示', { type: 'error' })
      }
    },
    // async getAllClass (okFun) {
    //   this.loading = true
    //   const res = await this.$api.plan.getAllClass.get(this.search)
    //   if (res.code === 200) {
    //     let dealData = []
    //     let dealAllClass = []
    //     let allGClassId = []
    //     res.data.depData.map(item => {
    //       if (item % 10 !== 0 && item.clasList.length !== 0) {
    //        let allClassId = []
    //        let allClass = []
    //        item.clasList.map(item => {
    //           let obj = {
    //                 clas_id: item.clas_id,
    //                 clas_name: item.clas_name
    //               }
    //               allClassId.push(item.clas_id)
    //               allClass.push(obj)
    //               allGClassId.push(item.clas_id)
    //        })
    //        item.clasList = allClass
    //        item.clasList.unshift({
    //                 clas_id: allClassId.join('_'),
    //                 clas_name: '全部班级'
    //               })
    //         dealAllClass[item.grade_id] = item.clasList
    //         dealData.push(item)
    //       }
    //     })

    //     this.allGrade = dealData
    //     this.allGrade.unshift({
    //       grade_id: 1000000,
    //       grade_name: '全部年级',
    //       clasList: [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //     })
    //     dealAllClass[1000000] = [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //     this.allClass = dealAllClass
    //     this.search.grade = 1000000
    //     console.log(dealData)
    //     this.search.search_class = allGClassId.join('_')
    //     this.getNowAllClass = [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //     // console.log(dealData)
    //     if (okFun) { okFun() }
    //   } else {
    //     this.loading = false
    //     this.$alert(res.message, '提示', { type: 'error' })
    //   }
    // },
    // async getGradeClass (gradeIds, okFun) {
    //   this.loading = true
    //   const res = await this.$api.plan.getAllClass.get({})
    //   if (res.code === 200) {
    //     let dealData = []
    //     let dealAllClass = []
    //     let allGClassId = []
    //     res.data.depData.map(item => {
    //       if (item % 10 !== 0 && item.clasList.length !== 0) {
    //         // 只有自己管理理论的年级才显示
    //         if (gradeIds.includes(item.grade_id)) {
    //             let allClassId = []
    //             let allClass = []
    //             item.clasList.map(item => {
    //                 let obj = {
    //                       clas_id: item.clas_id,
    //                       clas_name: item.clas_name
    //                     }
    //                     allClassId.push(item.clas_id)
    //                     allClass.push(obj)
    //                     allGClassId.push(item.clas_id)
    //             })

    //             item.clasList = allClass
    //             item.clasList.unshift({
    //                       clas_id: allClassId.join('_'),
    //                       clas_name: '全部班级'
    //                     })
    //               dealAllClass[item.grade_id] = item.clasList
    //               dealData.push(item)
    //         }
    //       }
    //     })

    //     this.allGrade = dealData
    //     this.allGrade.unshift({
    //       grade_id: 1000000,
    //       grade_name: '全部年级',
    //       clasList: [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //     })
    //     dealAllClass[1000000] = [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //     this.allClass = dealAllClass
    //     this.search.grade = 1000000
    //     this.search.search_class = allGClassId.join('_')
    //     this.getNowAllClass = [{
    //         clas_id: allGClassId.join('_'),
    //         clas_name: '全部班级'
    //       }]
    //       if (okFun) { okFun() }
    //   } else {
    //     this.loading = false
    //     this.$alert(res.message, '提示', { type: 'error' })
    //   }
    // },
    // gradeChange(val) {
    //   this.getNowAllClass = this.allClass[val]
    //   this.search.search_class = this.allClass[val][0].clas_id
    //   this.search.pageNo = 1
    //   this.list()
    // },
    // // 表格内开关事件
    async changeSwitch (val, row) {
      // 1.还原数据
      row.status = row.status === '1' ? '0' : '1'
      // 2.执行加载
      row.loading = true
      const res = await this.$api.add.switch.post({ modelId: row.id, status: val })
      if (res.code === 200) {
          delete row.loading
          row.status = val
          // this.$refs.table.refresh()
          this.$message.success(`操作成功:模板【${row.model_title} 】已${Number(val) === 0 ? '关闭' : '开启'}`)
      } else {
          row.is_using = val === '1' ? '0' : '1'
          this.$alert(res.message, '提示', { type: 'error' })
      }
    },
    // 复制
    handleCopy(row) {
      this.copyDialog = true
      this.copyForm = JSON.parse(JSON.stringify(row))
      this.copyForm.title = this.copyForm.model_title
      this.copyForm.model_title = this.copyForm.model_title+'【副本】'
    },
    async copySave() {
      const res = await this.$api.add.copy.post({ copyModelId: this.copyForm.id, modelTitle: this.copyForm.model_title })
      if (res.code === 200) {
        this.copyDialog = false
        this.list()
        this.$message.success(`操作成功:模板【${this.copyForm.title} 】已复制}`)
      } else {
          this.$alert(res.message, '提示', { type: 'error' })
      }
    },
    // 分页操作-修改显示页数-每页显示指定条数
    handleSizeChange (e) {
      this.search.pageNo = 1
      this.search.pageSize = e
      this.list()
    },
    // 分页操作-跳转到指定页 跳转到指定页数
    handleCurrentChange (e) {
      this.search.pageNo = e
      this.list()
    },
       // 重置搜索条件
    reList () {
      this.search.pageNo = 1
      this.list()
    },
    // 格式化参数【下载】下载用
    // parseParams (data) {
    //   try {
    //     let tempArr = []
    //     for (let i in data) {
    //       let key = encodeURIComponent(i)
    //       let value = encodeURIComponent(data[i])
    //       tempArr.push(key + '=' + value)
    //     }
    //     let urlParamsStr = tempArr.join('&')
    //     return urlParamsStr
    //   } catch (err) {
    //     return ''
    //   }
    // },
    reset () {
      window.location.reload()
    },
    // 弹出窗口 日期相关操作++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 关闭预览窗口
    close (e, info) {
      this.dialogInfoVisible = false
    },
    // 关闭预览窗口 提示
    handleClose (done) {
      this.$confirm('确认要关闭编辑窗口吗？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    // 输入校验 文档：校验文字<>& {} |*=;%  单行文本框禁止输入英文特殊字符<>&{}|*=;%
    checkText (string) {
      // const pattern = /[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g
      const pattern = /[`<>& {} |*=;%\s]/g
      const str = string.replace(pattern, '')
      this.dialogForm.plan_name = str
    },
    // A 数组 是否包含B数组
    arrayIncludes (arr1, arr2) {
      return arr2.every(val => arr1.includes(val))
    },

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 预览模板
    async handleView (e, info) {
      this.dialogInfoVisible = true
      this.sealShow = info.is_seal === 1
      this.time = info.insert_time_str
      this.org_name = info.org_name
      this.image = info.image
      this.nowView = JSON.parse(info.template_json)
    },
    // 删除模板
    async handleDel (info) {
      const delTitle =info.model_title
      //  this.$confirm('删除模板会同时删除相关的全部数据，确认要删除吗?', '提示', {
      //    confirmButtonText: '确定',
      //    cancelButtonText: '取消',
      //    type: 'warning'
      //  }).then(async () => {
      this.loading=true
      const delPr = { modelId: info.id }
      const res = await this.$api.add.del.post(delPr)
      this.loading=false
      if (res.code === 200) {
        this.list()
        this.$message.success(`操作成功:模板【${delTitle} 】已删除}`)
      } else {
        this.$alert(res.message, '提示', { type: 'error' })
      }
      //  }).catch(() => {
      //  })
    },
    handleEditOrAdd (obj) {
      this.$parent.$parent.editTemplate = obj?obj.id:null
      this.$parent.$parent.level2Text= obj?'编辑模板':'新增模版'
      sessionStorage.editTemplate = obj?obj.id:null
      sessionStorage.level2Text = obj?'编辑模板':'新增模版'
      window.location.href='#x45'
    }
  }
}
</script>
<style>
#app {
  font-family: Helvetica, sans-serif;
  text-align: center;
}

.el-table td,
.el-table th {
  padding: 5px 0;
  font-size: 14px;
}

.el-table td .el-button {
  padding: 8px 0px;
}

.el-link {
  margin-right: 10px;
}

.el-table__empty-block {
  max-height: 99px;
}

.el-textarea .el-input__count {
  background: none;
  bottom: -36px;
}

.el-dialog__body {
  padding: 0 30px;
  border: 1px #fff solid;
}

.checkSendObj .el-checkbox-group {
  margin-left: 21px;
  display: flex;
}

.search {
  background: #fbfafa;
  padding: 10px 12px 12px 12px;
  min-height: 30px;
  height: 36px;
  overflow: hidden;
}

.search .el-form-item {
  margin-bottom: 0;
}

.search .el-range-editor.el-input__inner {
  padding: 0px 10px;
  margin-top: 0px;
}

.el-pagination {
  padding: 18px 0px;
}

.checkSendObj .el-form-item__content {
  padding-left: 20px;
}

.search .el-form-item__content {
  padding-left: 0;
}

.el-popover {
  max-width: 240px;
}

.el-popconfirm__main {
  padding: 5px 0;
}

body {
  overflow: auto;
  background-color: #fff;
}

.fileInput input {
  border: none;
}

/* 统计信息 */
.echarsWrap {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  flex-direction: row;
  margin-bottom: 15px;
  position: relative;
  padding: 20px 20px 0px 20px;
}

.echarsWrap legend {
  color: #496f8f;
  font-weight: bold;
}

.echarsWrap fieldset {
  margin-left: 15px;
  background-image: -webkit-linear-gradient(330deg, #fbfdff, #e1e8ef);
  background-image: -o-linear-gradient(330deg, #fbfdff, #e1e8ef);
  background-image: linear-gradient(120deg, #fbfdff, #e1e8ef);
  background-size: cover;
  border-radius: 5px;
  overflow: hidden;
  padding: 0 40px 0px 20px;
  position: relative;
}

.oneEcharsShow .oneEcharsNum {
  font-size: 24px;
  font-family: "sans-serif";
  font-weight: bold;
  line-height: 44px;
  text-align: center;
  height: 48px;
}
.viewBG {
  padding:70px 22px 81px 22px;
  background: url(~@/assets/bgiphone.png) no-repeat;
  height: 628px;
  width: 340px;
}
.planTitleWrap .planTitle {
  font-weight: bold;
  font-size: 16px;
}

.echarsWrap .oneEcharsTitle {
  font-size: 12px;
  position: absolute;
  right: 20px;
  top: 20px;
}

.el-table .cell {
  line-height: 24px;
  transform: translate3d(0, 0, 0);
}

.el-picker-panel__footer button:first-child {
  display: none;
}

.el-table__fixed-right {
  min-height: 75px;
}
.el-image-viewer__actions,.el-image-viewer__close {
  overflow: hidden;
}
.imgList {
  display: inline-flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    text-align: center;
    overflow: hidden;
}
.imgList img {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: zoom-in;
}
.el-input--suffix .el-input__inner {
  padding-right: 6px;
}
.el-date-editor--daterange.el-input__inner {
  width: 280px;
}
.el-form--inline .el-form-item {
  margin-right: 2px;
}
.el-image-viewer__next, .el-image-viewer__prev,.el-image-viewer__close{
  display: -webkit-inline-box;
  overflow: hidden;
}
.temperature .el-input--suffix .el-input__suffix {
  top: -5px;
}
.temperature .el-input--suffix  .el-input-group__prepend .el-input__suffix {
  top: 5px;
}
.el-input-group__prepend {
  background: #fff;
}

.autoWidth {
  min-width: 120px;
  text-align: start;
}
.autoWidth .el-input__prefix {
  position: relative;
  box-sizing: border-box;
  border: 1px solid #ffffff00;
  padding: 0 40px;
  height: 40px;
  line-height: 40px;
  color: #606266;
  left: 0;
  visibility: hidden;
}
/* .autoWidth .el-input__inner {
  position: absolute;
} */

</style>
